package com.echat.messagesender.sender.email.impl;

import com.echat.commonlib.util.StringUtil;
import com.echat.messagesender.sender.email.EmailSender;
import com.echat.messagesender.sender.email.bean.EmailConfig;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by huangzhilin on 2018/5/10.
 */
public class CommonsEmailSender extends EmailSender {

    private static final Logger logger = LoggerFactory.getLogger(CommonsEmailSender.class);

    private EmailConfig mailConfig;

    public CommonsEmailSender() {
    }
    public CommonsEmailSender(EmailConfig config) {
        this.mailConfig = config;
        super.platformAccountId = config.getPlatformAccountId();
        super.platformName = config.getPlatformName();
    }

    @Override
    public boolean sendEmail(String[] receives, String subject, String htmlBody, String[] ccReceives, String[] bccReceivers, String replayEmail) {
        if (receives == null || StringUtil.isEmpty(htmlBody)) {
            return false;
        }
        try {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setCharset("utf-8");
            htmlEmail.addTo(receives);
            htmlEmail.setSubject(subject);
            htmlEmail.setHtmlMsg(htmlBody);
            if (ccReceives != null && ccReceives.length > 0) {
                htmlEmail.addCc(ccReceives);
            }
            if (bccReceivers != null && bccReceivers.length > 0) {
                htmlEmail.addBcc(bccReceivers);
            }
            if(StringUtil.isNotEmpty(replayEmail)){
                htmlEmail.addReplyTo(replayEmail);
            }
            sendEmail(htmlEmail);
        } catch (Exception e) {
            logger.error("CommonsEmailSender.sendHtmlEmail.error.", e);
            return false;
        }
        return true;
    }

    private void sendEmail(Email email) throws Exception {
        if (StringUtil.isNotEmpty(mailConfig.getEmailName())) {
            email.setFrom(mailConfig.getEmail(), mailConfig.getEmailName());
        } else {
            email.setFrom(mailConfig.getEmail());
        }
        email.setAuthentication(mailConfig.getEmail(), mailConfig.getPassword());
        email.setHostName(mailConfig.getSmtpHost());
        email.setSSLOnConnect(mailConfig.isSSLOnConnect());
        email.setStartTLSEnabled(mailConfig.isStartTLSEnabled());
        email.setStartTLSRequired(mailConfig.isStartTLSRequired());

        if (mailConfig.isSSLOnConnect()) {
            email.setSslSmtpPort(mailConfig.getSslSmtpPort());
        } else {
            if (mailConfig.getSmtpPort() != 0) {
                email.setSmtpPort(mailConfig.getSmtpPort());
            }
        }

        email.send();
    }
}
